﻿#region Imports

using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

#endregion

namespace bGallery.Core.Service
{
	/// <summary>
	/// Text util class
	/// </summary>
	public class TextUtil : ITextUtil
	{

		#region ITextUtil members

		/// <summary>
		/// Hash an input string and return the hash as
		/// a 32 character hexadecimal string.
		/// </summary>
		/// <param name="input">Input text to be hashed</param>
		/// <returns>32 character MD5 hash</returns>
		public string GetMd5Hash(string input)
		{
			// Create a new instance of the MD5CryptoServiceProvider object.
			MD5 md5Hasher = MD5.Create();

			// Convert the input string to a byte array and compute the hash.
			byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

			// Create a new Stringbuilder to collect the bytes
			// and create a string.
			StringBuilder sBuilder = new StringBuilder();

			// Loop through each byte of the hashed data 
			// and format each one as a hexadecimal string.
			for (int i = 0; i < data.Length; i++)
			{
				sBuilder.Append(data[i].ToString("x2"));
			}

			// Return the hexadecimal string.
			return sBuilder.ToString();
		}

		/// <summary>
		/// Gets URL friendly name
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public string GetUrlFriendlyName(string input)
		{
			return RemoveSpecialCharacters(RemoveDiacritics(input).Replace(' ', '-')).Trim(new char[] {'-'});
		}

		#endregion

		#region Private methods

		/// <summary>
		/// Removes accents form string
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		private static string RemoveDiacritics(string input)
		{
			string stFormD = input.Normalize(NormalizationForm.FormD);
			int len = stFormD.Length;
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < len; i++)
			{
				UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[i]);
				if (uc != UnicodeCategory.NonSpacingMark)
				{
					sb.Append(stFormD[i]);
				}
			}
			return (sb.ToString().Normalize(NormalizationForm.FormC));
		}

		/// <summary>
		/// Removes special characters from string
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		private static string RemoveSpecialCharacters(string input)
		{
			string cleanString = String.Empty;
			Regex reg = new Regex("[A-Z]|[a-z]|[0-9]|_|-");
			MatchCollection coll = reg.Matches(input);
			for (int i = 0; i < coll.Count; i++)
			{
				cleanString += coll[i].Value;
			}

			return cleanString;
		}

		#endregion
	}
}
